package com.garlic.face.jlf.transaction;

import android.app.Service;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;

import com.garlic.face.jlf.App;
import com.garlic.face.jlf.transaction.balance.MySQLiteOpenHelper;
import com.garlic.face.jlf.transaction.balance.database.GoodsWeight;
import com.garlic.face.jlf.transaction.balance.database.ItemExceptions;
import com.garlic.face.jlf.transaction.balance.greendao.gen.GoodsWeightDao;
import com.garlic.face.jlf.transaction.balance.greendao.gen.ItemExceptionsDao;
import com.garlic.face.jlf.utils.LogUtils;

import org.greenrobot.eventbus.EventBus;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by shiyanqi on 18/9/10.
 */

public class InsertSQLService extends Service {

	private SQLiteDatabase db;
	public static final String INSERT_GOODSWEIGHT_TABLE_SUCCESS = "insert_goodsweight_table_success";
	public static final String INSERT_GOODSWEIGHT_TABLE_FAILED = "insert_goodsweight_table_failed";
	public static final String INSERT_ITEMEXCEPTIONS_TABLE_SUCCESS = "insert_itemexceptions_table_success";
	public static final String INSERT_ITEMEXCEPTIONS_TABLE_FAILED = "insert_itemexceptions_table_failed";

	private InputStreamReader goodsWeightFs = null;
	private BufferedReader goodsWeightBr = null;
	private InputStreamReader itemExceptionsFs = null;
	private BufferedReader itemExceptionsBr = null;
	private GoodsWeightDao mGoodsWeightDao;
	private ItemExceptionsDao mItemExceptionsDao;

	@Nullable
	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	@Override
	public void onCreate() {
		super.onCreate();
		mGoodsWeightDao = App.getInstances().getDaoSession().getGoodsWeightDao();
		mItemExceptionsDao = App.getInstances().getDaoSession().getItemExceptionsDao();
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {

		db = App.getSQLiteOpenHelper().getWritableDatabase();
		new Thread(new Runnable() {
			@Override
			public void run() {
				executeAssetsGoodsWeight(db, "t_d_goodsweight.csv");
				executeAssetsItemExceptions(db, "t_d_itemexceptions.csv");
			}
		}).start();
		return START_STICKY;
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
	}


	/**
	 * 读取csv文件
	 * @param db
	 * @param csvfilepath assets下的*.csv文件路径
	 */
	public void executeAssetsGoodsWeight(SQLiteDatabase db, String csvfilepath) {
		try {
			//开启事务
			LogUtils.d("begin insert sql", true);
			db.beginTransaction();
			CSVAnalysisGoodsWeight(csvfilepath);
			//设置事务标志为成功，当结束事务时就会提交事务
			db.setTransactionSuccessful();
			LogUtils.d("insert sql success", true);
			EventBus.getDefault().post(INSERT_GOODSWEIGHT_TABLE_SUCCESS);
		} catch (Exception e) {
			LogUtils.e("db-error" + e.toString());
			EventBus.getDefault().post(INSERT_GOODSWEIGHT_TABLE_FAILED);
		} finally {
			//事务结束
			db.endTransaction();
		}
	}

	public void executeAssetsItemExceptions(SQLiteDatabase db, String csvfilepath) {
		try {
			//开启事务
			LogUtils.d("begin insert sql", true);
			db.beginTransaction();
			CSVAnalysisItemException(csvfilepath);
			//设置事务标志为成功，当结束事务时就会提交事务
			db.setTransactionSuccessful();
			LogUtils.d("insert sql success", true);
			EventBus.getDefault().post(INSERT_ITEMEXCEPTIONS_TABLE_SUCCESS);
		} catch (Exception e) {
			LogUtils.e("db-error" + e.toString());
			EventBus.getDefault().post(INSERT_ITEMEXCEPTIONS_TABLE_FAILED);
		} finally {
			//事务结束
			db.endTransaction();
		}
	}

	private void CSVAnalysisGoodsWeight(String csvfilepath){
		try {
			goodsWeightFs = new InputStreamReader(getAssets().open(csvfilepath));
			goodsWeightBr = new BufferedReader(goodsWeightFs);
			String rec = null;
			String[] argsArr = null;
			GoodsWeight goodsWeight = new GoodsWeight();
			while ((rec = goodsWeightBr.readLine()) != null) {
				argsArr = rec.split(",");
				goodsWeight.setId(argsArr[0].replace("\"", ""));
				goodsWeight.setBarcode(argsArr[1].replace("\"", ""));
				goodsWeight.setQty(argsArr[2] != null ? Integer.parseInt(argsArr[2].replace("\"", "")) : null);
				goodsWeight.setWeight(argsArr[3] != null ? Double.valueOf(argsArr[3].replace("\"", "")) : null);
				goodsWeight.setApprovedflag(argsArr[4].replace("\"", ""));
				goodsWeight.setDeviationtype(argsArr[5] != null ? Integer.valueOf(argsArr[9].replace("\"", "")) : null);
				goodsWeight.setAbs_deviation(argsArr[6] != null ? Double.valueOf(argsArr[6].replace("\"", "")) : null);
				goodsWeight.setPer_deviation(argsArr[7] != null ? Double.valueOf(argsArr[7].replace("\"", "")) : null);
				goodsWeight.setGoodsattr(argsArr[8].replace("\"", ""));
				goodsWeight.setRestype(argsArr[9] != null ? Integer.valueOf(argsArr[9].replace("\"", "")) : null);
				goodsWeight.setExpirydays(argsArr[10] != null ? Integer.valueOf(argsArr[10].replace("\"", "")) : null);
				goodsWeight.setSubcode(argsArr[11].replace("\"", ""));
				goodsWeight.setRemark(argsArr[12].replace("\"", ""));
				goodsWeight.setState(argsArr[13].replace("\"", ""));
				goodsWeight.setUpdate_name(argsArr[14].replace("\"", ""));
				goodsWeight.setUpdate_date(argsArr[15].replace("\"", ""));
				goodsWeight.setUpdate_by(argsArr[16].replace("\"", ""));
				goodsWeight.setCreate_name(argsArr[17].replace("\"", ""));
				goodsWeight.setCreate_date(argsArr[18].replace("\"", ""));
				goodsWeight.setCreate_by("");
				mGoodsWeightDao.insert(goodsWeight);
			}
		} catch (Exception e) {
			EventBus.getDefault().post(INSERT_GOODSWEIGHT_TABLE_FAILED);
			e.printStackTrace();
		}finally{
			try{
				if (goodsWeightFs != null )
					goodsWeightFs.close();
				if (goodsWeightBr != null )
					goodsWeightBr.close();
			}catch(IOException ex){
				ex.printStackTrace();
			}
		}
	}

	private void CSVAnalysisItemException(String csvfilepath){
		try {
			itemExceptionsFs = new InputStreamReader(getAssets().open(csvfilepath));
			itemExceptionsBr = new BufferedReader(itemExceptionsFs);
			String rec = null;
			String[] argsArr = null;
			ItemExceptions itemExceptions = new ItemExceptions();
			while ((rec = itemExceptionsBr.readLine()) != null) {
				argsArr = rec.split(",");
				itemExceptions.setId(argsArr[0].replace("\"", ""));
				itemExceptions.setBarcode(argsArr[1].replace("\"", ""));
				itemExceptions.setIncode(argsArr[2].replace("\"", ""));
				itemExceptions.setFname(argsArr[3].replace("\"", ""));
				itemExceptions.setExpectedweight(argsArr[4] != null ? Double.valueOf(argsArr[4].replace("\"", "")) : null);
				itemExceptions.setObservedweight(argsArr[5] != null ? Double.valueOf(argsArr[5].replace("\"", "")) : null);
				itemExceptions.setExceptiontype(argsArr[6] != null ? Integer.valueOf(argsArr[6].replace("\"", "")) : null);
				itemExceptions.setFlowno(argsArr[7].replace("\"", ""));
				itemExceptions.setPoscaseid(argsArr[8].replace("\"", ""));
				itemExceptions.setPoscode(argsArr[9].replace("\"", ""));
				itemExceptions.setEntrytime(argsArr[10].replace("\"", ""));
				itemExceptions.setCustid(argsArr[11].replace("\"", ""));
				itemExceptions.setOrgid(argsArr[12].replace("\"", ""));
				itemExceptions.setOperatorid("");
				mItemExceptionsDao.insert(itemExceptions);
			}
		} catch (Exception e) {
			EventBus.getDefault().post(INSERT_ITEMEXCEPTIONS_TABLE_FAILED);
			e.printStackTrace();
		}finally{
			try{
				if (itemExceptionsFs != null )
					itemExceptionsFs.close();
				if (itemExceptionsBr != null )
					itemExceptionsBr.close();
			}catch(IOException ex){
				ex.printStackTrace();
			}
		}
	}
}
